package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.controller.GoodsController.GoodsDetail.SubGoodsResponse
import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.entity.Goods
import com.zxy.supplier_system.server.entity.GoodsUnit
import com.zxy.supplier_system.server.entity.SubGoods
import com.zxy.supplier_system.server.repository.QueryGoodsUnitResponse
import com.zxy.supplier_system.server.service.MarketOrderService
import com.zxy.supplier_system.server.utils.LongIdAndName
import com.zxy.supplier_system.server.utils.displayCellString
import com.zxy.supplier_system.server.utils.nullIfBlank
import com.zxy.supplier_system.server.utils.toLongIdAndName
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

@RestController
@RequestMapping("markets/orders/{orderId}/items")
class MarketOrdersItemController(
    private val marketOrderService: MarketOrderService
) {

    data class AddMarketOrdersItemRequest(
        val goodsId: Int,
        val amount: Int,
        val unitId: Long?,
        val subGoodsId: Int?,
        val note: String?,
    )

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单, Authority.卖场_订单_添加货品)
    @PostMapping
    fun addItem(@PathVariable orderId: Int, @RequestBody addMarketOrdersItemRequest: AddMarketOrdersItemRequest) {
        this.marketOrderService.addItem(orderId, addMarketOrdersItemRequest)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单)
    @DeleteMapping("{goodsId}")
    fun deleteItem(@PathVariable goodsId: Int, @PathVariable orderId: Int) {
        this.marketOrderService.deleteItem(orderId, goodsId)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单)
    @DeleteMapping("{goodsId}/sub/{subGoodsId}")
    fun deleteItem(@PathVariable goodsId: Int, @PathVariable orderId: Int, @PathVariable subGoodsId: Int) {
        this.marketOrderService.deleteItem(orderId, goodsId, subGoodsId)
    }

    @Transactional
    class UpdateItemAmountRequest(
        val amount: Int,
        val unitId: Long?
    )

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单)
    @PatchMapping("{goodsId}/amount")
    fun updateItemAmount(
        @PathVariable goodsId: Int,
        @PathVariable orderId: Int,
        @RequestBody updateItemAmountRequest: UpdateItemAmountRequest
    ) {
        return this.marketOrderService.updateItemAmount(goodsId, orderId, updateItemAmountRequest)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单)
    @PatchMapping("{goodsId}/sub/{subGoodsId}/amount")
    fun updateItemAmount(
        @PathVariable goodsId: Int,
        @PathVariable orderId: Int,
        @RequestBody updateItemAmountRequest: UpdateItemAmountRequest,
        @PathVariable subGoodsId: Int
    ) {
        return this.marketOrderService.updateItemAmount(goodsId, orderId, subGoodsId, updateItemAmountRequest)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单)
    @PatchMapping("{goodsId}/note")
    fun updateItemNote(
        @PathVariable goodsId: Int,
        @PathVariable orderId: Int,
        @RequestBody note: String
    ) {
        return this.marketOrderService.updateItemNote(goodsId, orderId, note)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单)
    @PatchMapping("{goodsId}/sub/{subGoodsId}/note")
    fun updateItemNote(
        @PathVariable goodsId: Int,
        @PathVariable orderId: Int,
        @RequestBody note: String,
        @PathVariable subGoodsId: Int
    ) {
        return this.marketOrderService.updateItemNote(goodsId, orderId, subGoodsId, note)
    }

    @HasAuthority(Authority.卖场_订单_查询)
    @GetMapping
    fun queryOrderItemsInOrder(@PathVariable orderId: Int, pageable: Pageable): Page<OrderItemInOrderSummary> {
        return this.marketOrderService.queryOrderItemsInOrder(orderId, pageable)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单, Authority.卖场_订单_添加货品)
    @GetMapping("{goodsId}/exists")
    fun exists(@PathVariable goodsId: Int, @PathVariable orderId: Int): Boolean {
        return this.marketOrderService.exists(orderId, goodsId)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单, Authority.卖场_订单_添加货品)
    @GetMapping("barcodes/{barcode}/exists")
    fun exists(@PathVariable barcode: String, @PathVariable orderId: Int): Boolean {
        return this.marketOrderService.exists(orderId, barcode)
    }

    data class OrderItemInOrderSummary(
        val goodsId: Int,
        val name: String,
        val barcode: String,
        val amountInOrder: Int,
        val inStore: Int,
        val boxSpecification: String?,
        val units: List<QueryGoodsUnitResponse>,
        val unit: LongIdAndName?,
        val subGoods: SubGoodsResponse? = null,
    ) {
        companion object {

            fun fromGoodsAndAmountAndUnit(
                goods: Goods,
                amount: Int,
                goodsUnit: GoodsUnit?,
                subGoods: SubGoods? = null
            ): OrderItemInOrderSummary {
                return OrderItemInOrderSummary(
                    goods.id,
                    goods.name,
                    goods.barcode,
                    amount,
                    goods.amount,
                    goods.boxSpecification,
                    goods.units.map(QueryGoodsUnitResponse::formGoodsUnit),
                    goodsUnit?.toLongIdAndName(),
                    subGoods?.let(SubGoodsResponse::fromSubGoods)
                )
            }
        }
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单, Authority.卖场_订单_添加货品)
    @PostMapping("barcodes/{barcode}")
    fun addItem(@PathVariable barcode: String, @PathVariable orderId: Int): OrderItemInOrderSummary {
        return this.marketOrderService.addItem(orderId, barcode)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_转化为送货单, Authority.卖场_订单_添加货品)
    @PostMapping("goods/{goodsId}")
    fun addItem(@PathVariable goodsId: Int, @PathVariable orderId: Int): OrderItemInOrderSummary {
        return this.marketOrderService.addItem(orderId, goodsId)
    }

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_添加货品)
    @PostMapping("goods", params = ["goodsIds"])
    fun addItems(@PathVariable orderId: Int, @RequestParam goodsIds: MutableList<Int>): List<OrderItemInOrderSummary> {
        return this.marketOrderService.addItems(orderId, goodsIds)
    }

    data class AddOrderItemKey(
        val goodsId: Int,
        val subGoodsId: Int?,
    )

    @HasAnyAuthority(Authority.卖场_订单_下单, Authority.卖场_订单_添加货品)
    @PostMapping("batchAdd")
    fun batchAddItems(
        @PathVariable orderId: Int,
        @RequestBody itemKeys: MutableList<AddOrderItemKey>
    ): List<OrderItemInOrderSummary> {
        return this.marketOrderService.batchAddItems(orderId, itemKeys)
    }

    @HasAuthority(Authority.卖场_订单_添加货品)
    @PostMapping("excel/import")
    fun importFromExcel(@PathVariable orderId: Int,@RequestParam file: MultipartFile): Int {
        val workbook = WorkbookFactory.create(file.inputStream)
        val sheet = workbook.getSheetAt(0)

        val goodsItems = (1..sheet.lastRowNum).map(sheet::getRow).mapNotNull { row ->
            fun getCellValue(cellIndex: Int): String? {
                return row.getCell(cellIndex)?.displayCellString?.trim()
            }

            var cellIndex = 0
            val barcode = getCellValue(cellIndex++) ?: return@mapNotNull null
            val subGoodsNumber = getCellValue(cellIndex++)
            val amount = getCellValue(cellIndex++)?.toDoubleOrNull()?.toInt() ?: return@mapNotNull null
            val unit = getCellValue(cellIndex++)
            val note = getCellValue(cellIndex++)?.nullIfBlank()
            MarketOrderItemExcelItem(
                barcode,
                subGoodsNumber,
                amount,
                unit,
                note,
            )
        }

        return this.marketOrderService.importFromExcelItems(orderId,goodsItems)
    }

    data class MarketOrderItemExcelItem(
        val barcode:String,
        val subGoodsNumber:String?,
        val amount:Int,
        val unit:String?,
        val note:String?,
    )

}